<?php
//添加下单收货地址
function add_useraddr($info) {
	global $db, $user;
	if (pe_login('user')) {
		if ($info['address_default'] == 1) {
			$db->pe_update('useraddr', array('user_id'=>$user['user_id']), array('address_default'=>0));
		}
		$address_id = $db->pe_insert('useraddr', pe_dbhold($info));
	}
	else {
		$useraddr_list = pe_getcookie('pe_useraddr', 'array');
		if ($info['address_default'] == 1) {
			foreach ($useraddr_list as $k=>$v) {
				$useraddr_list[$k]['address_default'] = 0; 
			}
		}
		$info['address_id'] = $address_id = md5(time().rand(1,99999));
		$address_new = array($address_id=>$info);
		$useraddr_list = count($useraddr_list) ? array_merge($address_new, $useraddr_list) : $address_new;
		pe_setcookie('pe_useraddr', $useraddr_list);
	}
	if ($address_id) {
		pe_apidata(array('code'=>1, 'msg'=>'添加成功', 'data'=>array('id'=>$address_id)));
	}
	else {
		pe_apidata(array('code'=>0, 'msg'=>'添加失败'));
	}
}

//获取下单收货地址
function get_useraddr_list($address_id) {
	global $db, $user;
	$list = $info = array();
	if (pe_login('user')) {
		$list = $db->index('address_id')->pe_selectall('useraddr', array('user_id'=>$user['user_id'], 'order by'=>'address_default desc, address_id desc'));
	}
	else {
		$useraddr_list = pe_getcookie('pe_useraddr', 'array');
		foreach ($useraddr_list as $k=>$v) {
			if ($v['address_default']) {
				unset($useraddr_list[$k]);
				$address_default = array($k=>$v);
			}
		}
		$list = is_array($address_default) ? array_merge($address_default, $useraddr_list) : $useraddr_list;
	}
	$one = key($list);
	foreach ($list as $k=>$v) {
		if ($address_id && $address_id == $v['address_id']) {
			$list[$k]['sel'] = 1;
			$info = $v;
		}
		elseif (!$address_id && $one == $v['address_id']) {
			$list[$k]['sel'] = 1;
			$info = $v;			
		}
	}
	$info['list'] = array_values($list);
	return $info;
}

//获取下单地址详情
function get_useraddr_info($address_id) {
	global $db, $user;
	if (pe_login('user')) {
		$info = $db->pe_select('useraddr', array('user_id'=>$user['user_id'], 'address_id'=>intval($address_id)));
	}
	else {
		$info = array();
		$useraddr_list = pe_getcookie('pe_useraddr', 'array');
		foreach ($useraddr_list as $k=>$v) {
			if ($v['address_id'] == $address_id) {
				$info = $v;
				break;
			}
		}
	}
	return $info;
}